package cn.tworice.netty.config;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;

@Configuration
@Slf4j
public class NettyConfig {

    @Resource
    private NettyProperties nettyProperties;

    @Resource
    private WebSocketInitializer webSocketInitializer;
    /**
     * 用来处理连接建立和断开的线程
     **/
    @Bean
    public EventLoopGroup bossGroup() {
        return new NioEventLoopGroup(this.nettyProperties.getBoss());
    }

    @Bean
    public EventLoopGroup workerGroup() {
        return new NioEventLoopGroup(this.nettyProperties.getWork());
    }

    @Bean
    public ServerBootstrap serverBootstrap() {
        log.info("启动Netty服务在【{}】上", this.nettyProperties.getPort());
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup(), workerGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(this.webSocketInitializer)
                .option(ChannelOption.SO_BACKLOG, this.nettyProperties.getBacklog())
                .childOption(ChannelOption.SO_KEEPALIVE, this.nettyProperties.getKeepalive());
        return serverBootstrap;
    }

    @Bean
    public ChannelFuture startServer() {
        return serverBootstrap().bind(this.nettyProperties.getPort());
    }
}

